﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Transactions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;

public partial class Admin_Components_SaleOrder_SaleOrderBulk : System.Web.UI.UserControl
{
    DBDataContext db = LINQUtil.GetDBWriteOnly();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            this.txtCustomerCode.Focus();
            loadDataForm();
            LoadFormForCustomerTab();
            loadDataGrid();
            if (Session["SaleOrderID"] != null)
            {
                int ID = Convert.ToInt32(Session["SaleOrderID"]);
                ViewState["SaleOrderID"] = ID;
                Session["SaleOrderID"] = null;
                Session.Remove("SaleOrderID");
                loadDataView(ID);
            }
        }
    }
    private void loadDataView(int SaleOderID)
    {
        try
        {
            var so = db.SaleOrder_ById(SaleOderID, "").FirstOrDefault();

            txtSaleOrderStatus.Text = so.StatusDesc;
            cboShop.SelectedValue = so.ShopID.ToString();
            txtSaleOrderCode.Text = so.SaleOrderCode;
            txtCustomerCode.Text = so.CustomerCode;
            txtCustomerName.Text = so.CustomerName;
            cboIsReceiptBill.SelectedValue = so.IsReceiptBill == true ? "Y" : "N";

            txtReceiptAdress.Text = so.AddressReceipt;
            txtReceiptPerson.Text = so.PersonReceipt;
            txtReceiptPhoneNumer.Text = so.PhoneNumberReceipt;
            dtpReceiptDate.SelectedDate = so.DateTimeReceipt;
            ViewState["SaleOrderType"] = so.SaleOderType;
            cboSaleOrderType.SelectedValue = so.SaleOderType;
            cboEmployeeSale.SelectedValue = so.SaleEmployeeID.ToString();
            txtRemark.Text = so.Remark;
            this.cboVAT.Visible = bool.Parse(so.IsReceiptBill.ToString());
            //chi tiet sp
            
            var listProduct = (from list in db.SaleOrderDetails
                               join p in db.Products on list.ProductID equals p.ID
                               where list.SaleOrderID == SaleOderID
                               && p.Status == 'A'
                               select new
                               {
                                   list.ProductID,
                                   p.ProductName,
                                   ProductCode = p.ProductCode,
                                   list.Price,
                                   list.Weight,
                                   PackType = list.PackType,
                                   Quantity = list.Quantity,
                                   Total = list.Price * list.Weight,
                                   isPrice = so.SaleOderType == "B"?"true":"false"
                               }).ToList();

            DataTable dt = listProduct.ToDataTable();
            ViewState["CurrentTable"] = dt;
            gvData.DataSource = dt;
            gvData.DataBind();
            this.cboSaleOrderType.Enabled = false;
            // load du lieu tong
            CalSum(dt);
            //Xet câc button
            dispalyButton(so.Status, so.FormReceipt);
            //
        }
        catch (Exception ex)
        {
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Có lỗi xảy ra!");
            ControlUtil.LogError("-----------------------------");
            ControlUtil.LogError("SaleOrderBulk-loadDataView");
            ControlUtil.LogError(ex.ToString());
            ControlUtil.LogError("-----------------------------");
        }
    }

    private void loadDataGrid()
    {
        try
        {
            DataTable dt = createDataTable();
            if (dt.Rows.Count > 2)
            {
                gvData.Height = 120;
                gvData.ClientSettings.Scrolling.AllowScroll = true;
                gvData.ClientSettings.Scrolling.UseStaticHeaders = true;
            }

            ViewState["CurrentTable"] = dt;

            gvData.DataSource = dt;
            gvData.DataBind();
        }
        catch (Exception ex)
        {
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Có lỗi xảy ra!");
            ControlUtil.LogError("-----------------------------");
            ControlUtil.LogError("SaleOrderBulk-loadDataGrid");
            ControlUtil.LogError(ex.ToString());
            ControlUtil.LogError("-----------------------------");
        }
    }

    private void loadDataForm()
    {
        try
        {

           
            Utils.LoadCodeDetail(cboIsReceiptBill, "ReceiptBill", 0);
            cboIsReceiptBill.SelectedIndex = 1;

            int ShopID = Session["ShopID"] == null ? 0 : int.Parse(Session["ShopID"].ToString());
           
           
            //txtEmployeeBillName.Text = Session["UserName"].ToString();
            this.cboVAT.Visible = false;
            
            //Load shop
            int ProvinceID = Session["ProvinceID"] == null ? 0 : int.Parse(Session["ProvinceID"].ToString());

            int isShopAll = (ShopID == 0 ? 1 : 0);
            Utils.loadShopByProvinceToCombo(cboShop, isShopAll, ProvinceID, ShopID, "W");
            Utils.loadEmployeeToCombo(cboEmployeeSale, 0, 0, 1);
            dispalyButton('0', "");

            Utils.loadProductToCombo(cboProduct, 0, "R", int.Parse(cboShop.SelectedValue));
           // Utils.loadProductToCombo(cboProduct, 0, "R", ShopID);
            gv.DataSource = new DataTable();
            gv.DataBind();
        }
        catch (Exception ex)
        {
            // JavascriptUtil.LoadMessage(UpdatePanel1, false, ex.ToString());
            // Utils.ShowMessageBox(this.Page,ex.ToString());
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Có lỗi xảy ra!");
            ControlUtil.LogError("-----------------------------");
            ControlUtil.LogError("SaleOrder-loadDataForm");
            ControlUtil.LogError(ex.ToString());
            ControlUtil.LogError("-----------------------------");
        }
    }
    /*Khach hang*/
    private void LoadFormForCustomerTab()
    {
        Utils.loadLocation(cboProvince, 0, 1, 0);
        //Utils.loadLocation(cboDistrict, int.Parse(cboProvince.SelectedValue), 1, 0);
        gv.DataSource = new DataTable();
        gv.DataBind();
    }

    private void dispalyButton(char? Status, String FormReceipt)
    {
        if (Status != '0')
        {
            if (Status == 'N') // tao moi
            {
                btnCancel.Enabled = true;
                /*
                if (FormReceipt.ToLower() == "s")
                {
                    btnPayment.Enabled = true;
                }
                else
                {
                    btnPayment.Enabled = false;
                }
                 */ 
                btnPayment.Enabled = true;
                btnReturn.Enabled = false;
                this.txtSaleOrderStatus.Text = "Tạo mới";
            }
            else if (Status == 'T')//dang giao hang
            {
                btnSave.Enabled = false;
                btnCancel.Enabled = false;
                btnPayment.Enabled = true;
                btnReturn.Enabled = true;
                btnAddProduct.Enabled = false;
                this.txtSaleOrderStatus.Text = "Đang giao hàng";
            }
            else if (Status == 'C')//đã thanh toán
            {
                btnSave.Enabled = false;
                btnCancel.Enabled = false;
                btnPayment.Enabled = false;
                btnReturn.Enabled = true;
                
                btnAddProduct.Enabled = false;
                gv.Enabled = false;
                this.txtSaleOrderStatus.Text = "Đã thanh toán";
            }
            else if (Status == 'E')//Hủy bỏ
            {
                btnSave.Enabled = false;
                btnCancel.Enabled = false;
                btnPayment.Enabled = false;
                btnReturn.Enabled = false;
                
                btnAddProduct.Enabled = false;
                gv.Enabled = false;
                this.txtSaleOrderStatus.Text = "Hủy bỏ";
            }

            else if (Status == 'R')//Tra hang
            {
                btnSave.Enabled = false;
                btnCancel.Enabled = false;
                btnPayment.Enabled = false;
                btnReturn.Enabled = false;
                btnAddProduct.Enabled = false;
                gv.Enabled = false;
                this.txtSaleOrderStatus.Text = "Trả hàng";
            }

            if (Status == 'E' || Status == 'T' || Status == 'C' || Status == 'R')
            {
                this.RadPageView1.Enabled = false;
                this.RadPageView2.Enabled = false;
          
            }
        }
        else
        {
            btnCancel.Enabled = false;
            btnPayment.Enabled = false;
            btnReturn.Enabled = false;
            gv.Enabled = true;
        }
    }

    protected void btnPayment_Click(object sender, EventArgs e)
    {
        try
        {
            SaleOrder saleOrder = createSaleOrderObj();
            if (saleOrder.Status != 'C')//da thanh toan roi khong duoc thanh toan nua
            {
                saleOrder.PaymentDateTime = DateTime.Now;
                updateStatus('C', saleOrder);
                updateDiff();
            }
        }
        catch (Exception ex)
        {
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Có lỗi xảy ra!");
            ControlUtil.LogError("-----------------------------");
            ControlUtil.LogError("SaleOrderBulk-btnPayment_Click");
            ControlUtil.LogError(ex.ToString());
            ControlUtil.LogError("-----------------------------");
        }
    }
    private void updateDiff()
    {
        //update lai diem tich luy neu lech nhau
        try
        {
            db.ExecuteCommand("UpdateDataDiff");
        }
        catch (Exception ex)
        {
            // JavascriptUtil.LoadMessage(UpdatePanel1, false, "Có lỗi xảy ra!");
            ControlUtil.LogError("-----------------------------");
            ControlUtil.LogError("SaleOrder-UpdateDataDiff");
            ControlUtil.LogError(ex.ToString());
            ControlUtil.LogError("-----------------------------");
        }
    }
    protected void btnCancel_Click(object sender, EventArgs e)
    {
        var saleOrder = db.SaleOrders.FirstOrDefault<SaleOrder>(s => s.SaleOderCode == txtSaleOrderCode.Text);
        updateStatus('E', saleOrder);
    }
    protected void btnReturn_Click(object sender, EventArgs e)
    {
        var saleOrder = db.SaleOrders.FirstOrDefault<SaleOrder>(s => s.SaleOderCode == txtSaleOrderCode.Text);
        if (saleOrder != null && saleOrder.Status != 'R')//chi duoc tra hang 1 lan
        {
            updateStatus('R', saleOrder);
            updateDiff();
        }
        else
        {
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Đơn hàng này đã được trả hàng hoặc không tồn tại");
            ControlUtil.LogError("-----------------------------");
            ControlUtil.LogError("SaleOrderBulk-btnReturn_Click- SaleOrderCode:" + saleOrder.SaleOderCode + " double return");
            ControlUtil.LogError("-----------------------------");
        }
    }

    protected void btnCusSave_Click(object sender, EventArgs e)
    {
        Customer cus = createCustomer("1");
        if (cus != null)
        {
            String DistrictName = cboDistrict.SelectedItem.Text;
            String ProvinceName = cboProvince.SelectedItem.Text;
            string AddressFull = cus.Address + ", " + DistrictName + ", " + ProvinceName;

            this.txtReceiptPerson.Text = cus.CustomerName;
            this.txtReceiptPhoneNumer.Text = cus.PhoneNumber;
            this.txtReceiptAdress.Text = AddressFull;

            TabStrip1.SelectedIndex = 0;
            RadPageView1.Selected = true;
            this.txtCustomerName.Enabled = false;
            JavascriptUtil.LoadMessage(UpdatePanel1, true, "Tạo khách hàng thành công!");
        }
    }
    protected Customer createCustomer(string cusType)
    {
        try
        {
            DBDataContext dbread = LINQUtil.GetDBWriteOnly();
            Customer customer = new Customer();

            String CustomerName = "";
            String CustomerPhone = "";
            String Address = "";
            int DistrictID = 0;
            int ProvinceID = 0;
            if (cusType == "1")
            {
                CustomerName = Utils.KillChars(this.txtCustomerNameNew.Text.Trim());
                CustomerPhone = Utils.KillChars(this.txtPhoneNumber.Text.Trim());
                Address = Utils.KillChars(this.txtAddress.Text.Trim());
                DistrictID = Convert.ToInt32(this.cboDistrict.SelectedValue == "" ? "0" : this.cboDistrict.SelectedValue);
                ProvinceID = Convert.ToInt32(this.cboProvince.SelectedValue == "" ? "0" : this.cboProvince.SelectedValue);
                customer.CustType = "KH";
                //Check khong cho phep trung do dien thoai
                var check = (from cus in dbread.Customers
                             where cus.PhoneNumber == CustomerPhone
                             select cus).FirstOrDefault();
                if (check != null)
                {
                    JavascriptUtil.LoadMessage(UpdatePanel1, false, "Số điện thoại: " + CustomerPhone + " đã tồn tại. vui lòng chọn số khác");
                    return null;
                }
            }
            else // Khach le
            {
                CustomerName = "Khách lẻ";
                customer.CustType = "KL";
            }
            //Lay ma sau cung
            int lenZero = 7;//So ky tu khôg tính chữ cái đưungs đầu. ví dụ KH0000001 --> 7, k tính KH
            var customerCodeMax = dbread.Customers.Max(d => d.OrderNumber);
            int MaxOrderNumber = (customerCodeMax == null ? 0 : Convert.ToInt32(customerCodeMax)) + 1;
            String LastCode = ("000000" + MaxOrderNumber).ToString();
            String CustomerCode = "KH" + LastCode.Substring(LastCode.Length - lenZero);
            //End

            customer.CustomerCode = CustomerCode;
            customer.CustomerName = CustomerName;
            customer.PhoneNumber = CustomerPhone;
            customer.Address = Address;
            customer.DistrictID = DistrictID;
            customer.ProvinceID = ProvinceID;
            customer.AccumulateAmount = 0;
            customer.ConvertedAmount = 0;
            customer.RemainAmount = 0;
            customer.CreatedBy = Session["UserName"].ToString();
            customer.CreatedDateTime = DateTime.Now;
            customer.LastUpdatedBy = Session["UserName"].ToString();
            customer.LastUpdatedDateTime = DateTime.Now;
            customer.Status = 'A';
            customer.OrderNumber = MaxOrderNumber;
            dbread.Insert<Customer>(customer);
            dbread.SubmitChanges();
            this.txtCustomerCodeNew.Text = customer.CustomerCode;
            this.txtCustomerCode.Text = customer.CustomerCode;
            this.txtCustomerName.Text = customer.CustomerName;

            return customer;
        }
        catch (Exception ex)
        {
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Có lỗi xảy ra");
            ControlUtil.LogError("----------------------------");
            ControlUtil.LogError("SaleOrder-createCustomer");
            ControlUtil.LogError(ex.ToString());
            ControlUtil.LogError("----------------------------");
            return null;
        }
    }
    protected void gv_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
    {
        Loaddata();

    }
    private void Loaddata()
    {
        DBDataContext db = LINQUtil.GetDBWriteOnly();

        String CustomerCode = Utils.KillChars(this.txtCustomerCodeNew.Text.Trim());
        String CustomerName = Utils.KillChars(this.txtCustomerNameNew.Text.Trim());
        String CustomerPhone = Utils.KillChars(this.txtPhoneNumber.Text.Trim());
        int PageNumber = gv.CurrentPageIndex + 1;
        int PageSize = gv.PageSize;

        DateTime FromDate = new DateTime(2014, 06, 01);
        DateTime ToDate = new DateTime(2099, 12, 31);
        var q = db.Customer_Search(CustomerCode, CustomerName, CustomerPhone, "", 0, 0, FromDate, ToDate, PageSize, PageNumber).ToList();
        if (q.Count > 0)
        {
            gv.ClientSettings.Scrolling.UseStaticHeaders = true;
            gv.VirtualItemCount = q[0].TotalRows.Value;
            gv.DataSource = q;
            if (q.Count > 5)
            {
                //gv.Height = 120;
                gv.ClientSettings.Scrolling.AllowScroll = true;

                gv.ClientSettings.Scrolling.UseStaticHeaders = true;
            }
        }
        else
        {
            gv.DataSource = new DataTable();
        }
    }

    protected void btnCusSearch_Click(object sender, EventArgs e)
    {
        Loaddata();
        gv.DataBind();
    }
    protected void lnkCustomerCode_Click(object sender, EventArgs e)
    {
        LinkButton LNKCustomer = (LinkButton)sender;
        GridDataItem dataItem = (GridDataItem)LNKCustomer.NamingContainer;
        String CustomerName = dataItem["CustomerName"].Text;
        String CustomerCode = LNKCustomer.Text;
        String CustomerPhone = dataItem["PhoneNumber"].Text;


        this.txtCustomerCode.Text = CustomerCode;
        this.txtCustomerName.Text = CustomerName;
        String AddressFull = dataItem["Address"].Text + ", " + dataItem["District"].Text + ", " + dataItem["Province"].Text;

        this.txtReceiptPerson.Text = CustomerName;
        this.txtReceiptPhoneNumer.Text = CustomerPhone;
        this.txtReceiptAdress.Text = AddressFull;

        TabStrip1.SelectedIndex = 0;
        RadPageView1.Selected = true;
        this.txtCustomerName.Enabled = false;
        // Session["Cus"] = CustomerCode + "@" + CustomerName;
        // ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "ClientClose2", "ClientClose2('" + CustomerCode + "','" + CustomerName + "');", true);
        //ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "ClientClose2", "ClientClose2('" + CustomerCode + "','" + CustomerName + "','" + CustomerPhone + "','" + AddressFull + "');", true);
    }
    protected void cboProvince_SelectedIndexChanged(object sender, EventArgs e)
    {
        string provinceID = cboProvince.SelectedValue;
        Utils.loadLocation(cboDistrict, int.Parse(provinceID), 0, 0);
    }
    
    protected void btnAdd_Click(object sender, EventArgs e)
    {
        //RadWindowManager.Windows.Clear();

        if (this.cboShop.SelectedValue.Trim() == "0" || this.cboShop.SelectedValue.Trim() == "")
        {
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Vui lòng chọn cửa hàng");
            this.cboShop.Focus();
            return;
        }
        if (this.cboSaleOrderType.SelectedValue.Trim() == "0" || this.cboSaleOrderType.SelectedValue.Trim() == "")
        {
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Vui lòng chọn loại đơn hàng");
            this.cboSaleOrderType.Focus();
            return;
        }
        try
        {
            string productIDValue = cboProduct.SelectedValue;
            string productName = cboProduct.SelectedItem.Text;
            string Quantity = txtWeight.Text;
            string productID = productIDValue.Split('|')[0];
            string packType = productIDValue.Split('|')[1];
            int? warehouseQty = CheckWarehouse(int.Parse(productID), int.Parse(cboShop.SelectedValue), int.Parse(Quantity), int.Parse(packType));
            if (warehouseQty != -1)//so luong ton kho khong du
            {
                JavascriptUtil.LoadMessage(UpdatePanel1, false, "Sản phẩm " + productName + " không đủ số lượng tồn kho. SL tồn kho hiện tại:" + warehouseQty.ToString());
                return;
            }
            if (productID != "")
            {
                if (ViewState["CurrentTable"] != null)
                {
                    DataTable dt = (DataTable)ViewState["CurrentTable"];
                    //check ma san pham da chon chua
                    DataRow[] rows = dt.Select("ProductID='" + productID + "' AND PackType='" + packType + "'");
                    if (rows.Count() > 0)
                    {
                        rows[0].Delete();
                        dt.AcceptChanges();
                    }

                    var location = db.Shops.FirstOrDefault(s => s.ID == int.Parse(this.cboShop.SelectedValue));

                    if (location == null)
                    {
                        JavascriptUtil.LoadMessage(UpdatePanel1, false, "Cửa hàng chưa có dữ liệu tỉnh thành");
                        return;
                    }

                   
                    var pro = (from p in db.Products
                               where p.ID == Convert.ToInt32(productID)
                               && p.Status == 'A'
                               select p).FirstOrDefault();


                    if (pro != null)
                    {
                        DataRow drNew = dt.NewRow();

                       // drNew["IsPromotion"] = pro.IsPromotion;
                        drNew["ProductID"] = pro.ID;
                        drNew["ProductCode"] = pro.ProductCode;
                        drNew["ProductName"] = pro.ProductName;
                       // drNew["Price"] = String.Format("{0:#,#.##}", price.Price);
                        drNew["Price"] = 0;
                        drNew["Quantity"] = Quantity;
                        drNew["PackType"] = packType;
                        drNew["isPrice"] = this.cboSaleOrderType.SelectedValue == "B"?"true":"false";
                        
                        drNew["Weight"] = (int.Parse(Quantity) * int.Parse(packType)).ToString();
                       // double total = Convert.ToDouble(drNew["Weight"]) * Convert.ToDouble(price.Price);
                        drNew["Total"] = 0.ToString();//String.Format("{0:#,#.##}", total); 
                        dt.Rows.Add(drNew);
                        ViewState["CurrentTable"] = dt;
                    }
                    gvData.DataSource = dt;
                    gvData.DataBind();
                    this.cboSaleOrderType.Enabled = false;
                    CalSum(dt);

                    btnPayment.Enabled = false;
                    btnReturn.Enabled = false;
                }
            }
        }
        catch (Exception ex)
        {
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Có lỗi xảy ra!");
            ControlUtil.LogError("-----------------------------");
            ControlUtil.LogError("SaleOrderBulk-btnAdd_Click");
            ControlUtil.LogError(ex.ToString());
            ControlUtil.LogError("-----------------------------");
        }
    }
    private void CalSum(DataTable dt)
    {
        try
        {
            decimal vat = decimal.Parse(this.cboIsReceiptBill.SelectedValue.ToLower() == "n" ? "0" : this.cboVAT.SelectedValue);

            var sum = dt.AsEnumerable().Sum(dr => DecimalOrNull(dr["Total"]));
            var weight = dt.AsEnumerable().Sum(dr => DecimalOrNull(dr["Weight"]));
            total.InnerText = "0";
            totalTax.InnerText = "0";
            if (sum > 0)
            {
                sumTotal.InnerText = "Tổng: " + String.Format("{0:#,#.##}", sum) + " VNĐ";
            }
            if (vat != 0)
            {
                sumTotalTax.Visible = true;
                if (sum > 0)
                {
                    sumTotalTax.InnerText = "Tổng sau thuế: " + String.Format("{0:#,#.##}", sum * (vat + 1)) + " VNĐ";
                }
            }
            else
            {
                sumTotalTax.Visible = false;
            }
            total.InnerText = sum.ToString();
            totalTax.InnerText = (sum * (vat + 1)).ToString();
            sumWeight.InnerText = weight.ToString();
        }
        catch (Exception ex)
        {
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Có lỗi xảy ra!");
            ControlUtil.LogError("-----------------------------");
            ControlUtil.LogError("SaleOrderBulk-CalSum");
            ControlUtil.LogError(ex.ToString());
            ControlUtil.LogError("-----------------------------");
        }
    }

    protected void btnReset_Click(object sender, EventArgs e)
    {
        // RadWindowManager.Windows.Clear();
        Session["Cus"] = null;
        Response.Redirect("~/don-hang-ban-buon", true);
        // ViewState["dtPromotion"] = null;
        //loadDataForm();
    }

    protected void cboShop_SelectedIndexChanged(object sender, EventArgs e)
    {
        int ShopID = Session["ShopID"] == null ? 0 : int.Parse(Session["ShopID"].ToString());
        
        Utils.loadProductToCombo(cboProduct, 0, "R", int.Parse(this.cboShop.SelectedValue));
   
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        using (var transation = new TransactionScope())
        {
            try
            {
                /*
                if (txtCustomerCode.Text == "")
                {
                    createCustomer("2");
                }
                 */
                if (gvData.Items.Count > 0)
                {

                    SaleOrder saleOrder = createSaleOrderObj();

                    //string saleOrderCode = this.txtSaleOrderCode.Text;
                    string saleOrderCodeStatus = this.txtSaleOrderStatus.Text;
                    if (saleOrderCodeStatus == "")//Tao moi
                    {
                        db.Insert<SaleOrder>(saleOrder);
                    }
                    else // Cap nhat
                    {
                        DeleteDetail(saleOrder.ID);
                    }
                    updateStatus('N', saleOrder);
                    //chi tiet sp
                    List<SaleOrderDetail> listDetail = new List<SaleOrderDetail>();
                    foreach (GridDataItem it in gvData.Items)
                    {
                        SaleOrderDetail soDetail = new SaleOrderDetail();
                        soDetail.SaleOrderID = saleOrder.ID;
                        soDetail.ProductID = int.Parse(it["ProductID"].Text);
                        soDetail.Price = double.Parse(((RadNumericTextBox)it.FindControl("txtPrice")).Text.Replace(",", ""));
                        soDetail.PackType = int.Parse(it["PackType"].Text);
                        soDetail.Quantity = int.Parse(it["Quantity"].Text);
                        double? PurchasePrice = (from w in db.Warehouses where w.ProductID == int.Parse(it["ProductID"].Text) && w.PackType == soDetail.PackType && w.ShopID == int.Parse(this.cboShop.SelectedValue) select w.PurchasePrice).FirstOrDefault();
                        soDetail.PurchasePrice = PurchasePrice;
                        double weight = double.Parse(it["Weight"].Text.Replace(",", ""));
                        soDetail.Weight = weight;
                        soDetail.Amount = soDetail.Price * weight;
                        soDetail.CreatedBy = Session["UserName"].ToString();
                        soDetail.LastUpdatedBy = Session["UserName"].ToString();
                        soDetail.CreatedDateTime = DateTime.Now;
                        soDetail.LastUpdatedDateTime = DateTime.Now;
                        soDetail.Status = 'N';

                        listDetail.Add(soDetail);
                    }
                    db.Insert<SaleOrderDetail>(listDetail);

                    db.SubmitChanges();
                    transation.Complete();
                    this.txtSaleOrderCode.Text = saleOrder.SaleOderCode;
                    this.txtSaleOrderCode.ReadOnly = true;
                    this.txtCustomerCode.ReadOnly = true;
                    this.txtCustomerName.ReadOnly = true;
                    JavascriptUtil.LoadMessage(UpdatePanel1, true, "Thành công");
                    TabStrip1.SelectedIndex = 0;
                    RadPageView1.Selected = true;
                }
                else
                {
                    JavascriptUtil.LoadMessage(UpdatePanel1, false, "Danh sách sản phẩm không được trống");
                }
            }
            catch (Exception ex)
            {
                JavascriptUtil.LoadMessage(UpdatePanel1, false, "Có lỗi xảy ra!");
                ControlUtil.LogError("-----------------------------");
                ControlUtil.LogError("SaleOrderBulk-btnSave_Click");
                ControlUtil.LogError(ex.ToString());
                ControlUtil.LogError("-----------------------------");
                //return;
            }
        }
    }
    private SaleOrder createSaleOrderObj()
    {
        SaleOrder saleOrder = new SaleOrder();
        try
        {
            string saleOrderCode = this.txtSaleOrderCode.Text;
            if (saleOrderCode == "")
            {
                //Lay ma sau cung
                int lenZero = 8;//So ky tu khôg tính chữ cái đưungs đầu. ví dụ KH0000001 --> 7, k tính KH
                var CodeMax = db.SaleOrders.Max(d => d.OrderNumber);
                int MaxOrderNumber = (CodeMax == null ? 0 : Convert.ToInt32(CodeMax)) + 1;
                String LastCode = ("00000000" + MaxOrderNumber).ToString();
                String Code = "DH" + LastCode.Substring(LastCode.Length - lenZero);
                //End
                saleOrder.OrderNumber = MaxOrderNumber;
                saleOrder.SaleOderCode = Code;
                saleOrder.Status = 'N';
            }
            else
            {
                saleOrder = db.SaleOrders.FirstOrDefault<SaleOrder>(so => so.SaleOderCode == saleOrderCode);
            }

            //var CustomerID = (from c in db.Customers where c.CustomerCode == this.txtCustomerCode.Text.Trim() select c.ID).FirstOrDefault();
            var CustomerID = 0;
            if (txtCustomerCode.Text == "")
            {
                Customer cus = createCustomer("2");
                CustomerID = cus.ID;
            }
            else
            {
                CustomerID = (from c in db.Customers where c.CustomerCode == this.txtCustomerCode.Text.Trim() select c.ID).FirstOrDefault();
            }
            if (CustomerID == 0)
            {
                JavascriptUtil.LoadMessage(UpdatePanel1, false, "Có lỗi xảy ra trong quá trình tạo khách hàng.Vui lòng thử lại!");
                return null;
            }
            saleOrder.SaleOrderRequestID = 0;
            saleOrder.CustomerID = CustomerID;
            saleOrder.IsReceiptBill = (this.cboIsReceiptBill.SelectedValue.ToLower() == "n" ? false : true);
            saleOrder.DeliveryEmployeeID = 0;
            saleOrder.FormReceipt = "H";
            saleOrder.SaleOderType = this.cboSaleOrderType.SelectedValue;
            saleOrder.DiscountAmount =0;
            saleOrder.Amount = double.Parse(total.InnerText == "" ? "0" : total.InnerText);
            saleOrder.Total = double.Parse(totalTax.InnerText == "" ? "0" : totalTax.InnerText);
            saleOrder.VAT = double.Parse(this.cboIsReceiptBill.SelectedValue.ToLower() == "n" ? "0" : this.cboVAT.SelectedValue);
            saleOrder.ShopID = int.Parse(cboShop.SelectedValue);
            saleOrder.TotalWeight = Convert.ToInt32(sumWeight.InnerText);
            //thong tin giao hang
            saleOrder.PersonReceipt = txtReceiptPerson.Text.Trim();
            saleOrder.PhoneNumberReceipt = txtReceiptPhoneNumer.Text.Trim();
            saleOrder.AddressReceipt = txtReceiptAdress.Text.Trim();
            saleOrder.DateTimeReceipt = dtpReceiptDate.SelectedDate;
            saleOrder.SaleEmployeeID = int.Parse(cboEmployeeSale.SelectedValue);
            saleOrder.Remark = txtRemark.Text;
            saleOrder.CreatedBy = Session["UserName"].ToString();
            saleOrder.LastUpdatedBy = Session["UserName"].ToString();
            saleOrder.CreatedDateTime = DateTime.Now;
            saleOrder.LastUpdatedDateTime = DateTime.Now;
           
        }
        catch (Exception ex)
        {
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Có lỗi xảy ra!");
            ControlUtil.LogError("-----------------------------");
            ControlUtil.LogError("SaleOrderBulk-createSaleOrderObj");
            ControlUtil.LogError(ex.ToString());
            ControlUtil.LogError("-----------------------------");
        }
        return saleOrder;
    }
    protected void txtPrice_TextChanged(object sender, EventArgs e)
    {
        try
        {
            RadNumericTextBox objPrice = (RadNumericTextBox)sender;
            string price = objPrice.Text == "" ? "0" : objPrice.Text;
            GridDataItem dataItem = (GridDataItem)objPrice.NamingContainer;
            string Weight = dataItem["Weight"].Text;
            string productID = dataItem["ProductID"].Text;
            string packType = dataItem["PackType"].Text;
            //dataItem["Total"].Text = (int.Parse(price.Replace(",", "")) * int.Parse(Weight.Replace(",", ""))).ToString("#,###");

            if (ViewState["CurrentTable"] != null)
            {
                DataTable dt = (DataTable)ViewState["CurrentTable"];
                DataRow[] rows = dt.Select("ProductID='" + productID + "' AND PackType='" + packType + "'");
                if (rows.Count() > 0)
                {
                    DataRow row = rows[0];
                    row["Total"] = (int.Parse(price.Replace(",", "")) * int.Parse(Weight.Replace(",", ""))).ToString();
                    row["Price"] = double.Parse(price);
                }
                gvData.DataSource = dt;
                gvData.DataBind();
                CalSum(dt);
            }
        }
        catch (Exception ex)
        {
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Có lỗi xảy ra!");
            ControlUtil.LogError("-----------------------------");
            ControlUtil.LogError("SaleOrderBulk-txtPrice_TextChanged");
            ControlUtil.LogError(ex.ToString());
            ControlUtil.LogError("-----------------------------");
        }
    }
    protected void cboIsReceiptBill_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
    {
        string isBill = this.cboIsReceiptBill.SelectedValue;
        decimal vat = decimal.Parse(this.cboIsReceiptBill.SelectedValue.ToLower() == "n" ? "0" : this.cboVAT.SelectedValue);
        if (isBill.ToString().ToLower() == "n")
        {
            this.cboVAT.Visible = false;

        }
        else
        {
            this.cboVAT.Visible = true;
        }
        DataTable dt = (DataTable)ViewState["CurrentTable"];
        CalSum(dt);
       // CalsumHelp(DecimalOrNull(this.DivAccumulateAmount.InnerText == "" ? "0" : this.DivAccumulateAmount.InnerText), vat, double.Parse(this.DivDiscountAmount.InnerText == "" ? "0" : this.DivDiscountAmount.InnerText));
    }
    protected void grvData_ItemCommand(object sender, GridCommandEventArgs e)
    {

        string commandName = e.CommandName;
        string ProductID_PackType = e.CommandArgument.ToString();
        string ProductID = ProductID_PackType.Split('-')[0];
        string PackType = ProductID_PackType.Split('-')[1];
        if (commandName == "DelItem")
        {
            DataTable dt = (DataTable)ViewState["CurrentTable"];

            DataRow[] rows = dt.Select("ProductID='" + ProductID + "' AND PackType='" + PackType + "'");
            foreach (DataRow r in rows)
            {
                r.Delete();
                dt.AcceptChanges();
            }
            ViewState["CurrentTable"] = dt;
            gvData.DataSource = dt;
            gvData.DataBind();
            CalSum(dt);
        }
        else if (commandName == "EditItem")
        {
            DataTable dt = (DataTable)ViewState["CurrentTable"];
            DataRow[] rows = dt.Select("ProductID='" + ProductID + "' AND PackType='" + PackType + "'");
            if (rows.Count() > 0)
            {
                this.cboProduct.SelectedValue = ProductID + "|" + PackType;
                this.txtWeight.Text = rows[0]["Quantity"].ToString();
            }
        }

    }
    private DataTable createDataTable(bool isFirst = true)
    {
        DataTable dt = new DataTable();
        if (ViewState["CurrentTable"] == null)
        {
            dt.Columns.Add("ProductID");
            dt.Columns.Add("ProductCode");
            dt.Columns.Add("ProductName");
            dt.Columns.Add("Price");
            dt.Columns.Add("PackType");
            dt.Columns.Add("Quantity");
            dt.Columns.Add("Weight");
            dt.Columns.Add("Total");
           // dt.Columns.Add("IsPromotion");
            dt.Columns.Add("isPrice");
            
        }
        else
        {
            dt = (DataTable)ViewState["CurrentTable"];
        }
        return dt;
    }
    private void DeleteDetail(int? saleOrderID)
    {
        try
        {
            List<SaleOrderDetail> soDetail = (from sd in db.SaleOrderDetails where sd.SaleOrderID == saleOrderID select sd).ToList<SaleOrderDetail>();
            db.Delete<SaleOrderDetail>(soDetail);
        }
        catch (Exception ex)
        {
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Có lỗi xảy ra!");
            ControlUtil.LogError("-----------------------------");
            ControlUtil.LogError("SaleOrderBulk-DeleteDetail");
            ControlUtil.LogError(ex.ToString());
            ControlUtil.LogError("-----------------------------");
        }
    }
    private int? CheckWarehouse(int productID, int shopID, decimal Qty, int packType)
    {
        int? result = -1;
        try
        {
            if (Qty > 0)
            {
                var wh = db.Warehouses.FirstOrDefault<Warehouse>(w => w.ProductID == productID && w.ShopID == shopID && w.PackType == packType);
                if (wh != null)
                {
                    if (wh.Quantity < Qty)
                    {
                        result = wh.Quantity;
                    }
                }
                else
                {
                    result = 0;
                }
            }
        }
        catch (Exception ex)
        {
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Có lỗi xảy ra!");
            ControlUtil.LogError("-----------------------------");
            ControlUtil.LogError("SaleOrderBulk-CheckWarehouse");
            ControlUtil.LogError(ex.ToString());
            ControlUtil.LogError("-----------------------------");
        }
        return result;
    }
    private void updateStatus(char status, SaleOrder saleOrder)
    {
        try
        {
            bool result = true;
            if (saleOrder != null)
            {
                char? StatusBeforeReturn = saleOrder.Status;
                saleOrder.Status = status;

                saleOrder.LastUpdatedBy = Session["UserName"].ToString();
                saleOrder.LastUpdatedDateTime = DateTime.Now;

                if (saleOrder.Status == 'C')//Hoan tat
                {
                    result = InOutWarehouse("O", saleOrder);
                }
                else if (status == 'R')//Tra hang va o trang thai da thanh toan thi  return lai so luong
                {
                    saleOrder.StatusBeforeReturn = StatusBeforeReturn;
                    if (StatusBeforeReturn == 'C')
                    {
                        result = InOutWarehouse("I", saleOrder);
                    }
                }
                if (result == true)
                {
                    db.Update<SaleOrder>(saleOrder);
                    db.SubmitChanges();
                    dispalyButton(saleOrder.Status, saleOrder.FormReceipt);
                }
                else
                {
                    JavascriptUtil.LoadMessage(UpdatePanel1, false, "Lỗi, thất bại. vui lòng thử lại hoặc liên hệ admin");
                    return;
                }
                JavascriptUtil.LoadMessage(UpdatePanel1, true, "Thành công!");
            }
        }
        catch (Exception ex)
        {
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Có lỗi xảy ra!");
            ControlUtil.LogError("-----------------------------");
            ControlUtil.LogError("SaleOrderBulk-updateStatus");
            ControlUtil.LogError(ex.ToString());
            ControlUtil.LogError("-----------------------------");
        }
    }

    //Tru kho -->ban hang, cong kho-->Tra hang
    private bool InOutWarehouse(string type, SaleOrder saleOrder)
    {
        bool result = true;
        if (type == "O")// ban hang
        {
            try
            {
                //Tru kho sp ban
                List<Warehouse> listWarehouse = new List<Warehouse>();
                var listSaleOrderDetail = (from l in db.SaleOrderDetails
                                           join p in db.Products on l.ProductID equals p.ID
                                           where l.SaleOrderID == saleOrder.ID && p.Status == 'A'
                                           select new
                                           {
                                               l.ProductID,
                                               l.PackType,
                                               l.Quantity,
                                               p.ProductName
                                           }).ToList();
                foreach (var soDetail in listSaleOrderDetail)
                {
                    var warehouse = db.Warehouses.FirstOrDefault<Warehouse>(w => w.ProductID == soDetail.ProductID && w.PackType == soDetail.PackType && w.Status == 'A' && w.ShopID == saleOrder.ShopID);
                    if (warehouse == null)
                    {
                        JavascriptUtil.LoadMessage(UpdatePanel1, false, "Sản phẩm " + soDetail.ProductName + " không tồn kho!");
                        return result = false;
                    }
                    warehouse.Quantity = warehouse.Quantity - IntOrNull(soDetail.Quantity);
                    if (warehouse.Quantity < 0)
                    {
                        JavascriptUtil.LoadMessage(UpdatePanel1, false, "số lượng gạo " + soDetail.ProductName + " tồn kho không đủ, vui lòng kiểm tra lại số lượng gạo tồn kho");
                        return result = false;
                    }
                    warehouse.LastUpdatedBy = Session["UserName"].ToString();
                    warehouse.LastUpdatedDateTime = DateTime.Now;
                    if (warehouse.Quantity == 0)
                    {
                        warehouse.PurchasePrice = 0;
                    }
                    listWarehouse.Add(warehouse);
                }
                /*
                ///Update diem tich luy cho khach hang
                var cus = db.Customers.FirstOrDefault(c => c.CustomerCode == this.txtCustomerCode.Text);
                cus.AccumulateAmount = cus.AccumulateAmount + double.Parse(total.InnerText);
                cus.ConvertedAmount = 0;
                cus.RemainAmount = cus.AccumulateAmount - cus.ConvertedAmount;
                cus.LastUpdatedBy = Session["UserName"].ToString();
                cus.LastUpdatedDateTime = DateTime.Now;

                db.Update<Customer>(cus);
                 */ 
                db.Update<Warehouse>(listWarehouse);
            }

            catch (Exception ex)
            {
                JavascriptUtil.LoadMessage(UpdatePanel1, false, "Có lỗi xảy ra!");
                ControlUtil.LogError("-----------------------------");
                ControlUtil.LogError("SaleOrderBulk-Sale-InOutWarehouse");
                ControlUtil.LogError(ex.ToString());
                ControlUtil.LogError("-----------------------------");
                return result = false;
            }
        }
        else//tra hang
        {
            try
            {
                //Tra so luong sp bán ve kho
                List<SaleOrderDetail> listSaleOrderDetail = (from l in db.SaleOrderDetails where l.SaleOrderID == saleOrder.ID select l).ToList<SaleOrderDetail>();
                List<Warehouse> listWarehouse = new List<Warehouse>();
                foreach (SaleOrderDetail soDetail in listSaleOrderDetail)
                {
                    var warehouse = db.Warehouses.FirstOrDefault<Warehouse>(w => w.ProductID == soDetail.ProductID && w.PackType == soDetail.PackType && w.Status == 'A' && w.ShopID == saleOrder.ShopID);
                    if (warehouse == null)
                    {
                        JavascriptUtil.LoadMessage(UpdatePanel1, false, "Sản phẩm không tồn kho!");
                        return result = false;
                    }
                    //neu gia von = 0 thi lay gia von cua chi tiet ban hang
                    if (warehouse.Quantity == 0)
                    {
                        warehouse.PurchasePrice = soDetail.PurchasePrice;
                    }

                    warehouse.Quantity = warehouse.Quantity + IntOrNull(soDetail.Quantity);
                    warehouse.LastUpdatedBy = Session["UserName"].ToString();
                    warehouse.LastUpdatedDateTime = DateTime.Now;

                    listWarehouse.Add(warehouse);
                }
                /*
                //tru tong tien tich luy
                var cus = db.Customers.FirstOrDefault(c => c.CustomerCode == this.txtCustomerCode.Text);
                cus.AccumulateAmount = cus.AccumulateAmount - double.Parse(total.InnerText);
                cus.ConvertedAmount = 0;
                cus.RemainAmount = cus.AccumulateAmount - cus.ConvertedAmount;
                cus.LastUpdatedBy = Session["UserName"].ToString();
                cus.LastUpdatedDateTime = DateTime.Now;
               
                db.Update<Customer>(cus);
                 */ 
                db.Update<Warehouse>(listWarehouse);

            }
            catch (Exception ex)
            {
                JavascriptUtil.LoadMessage(UpdatePanel1, false, "Có lỗi xảy ra!");
                ControlUtil.LogError("-----------------------------");
                ControlUtil.LogError("SaleOrderBulk-Return-InOutWarehouse");
                ControlUtil.LogError(ex.ToString());
                ControlUtil.LogError("-----------------------------");
                return result = false;
            }
        }
        return result;
        //db.SubmitChanges();
    }

    private decimal? DecimalOrNull(object val)
    {
        try
        {
            return Convert.ToDecimal(val);
        }
        catch
        {
            return null;
        }
    }

    private int? IntOrNull(object val)
    {
        try
        {
            return Convert.ToInt32(val);
        }
        catch
        {
            return null;
        }
    }
}